//
//  gerenViewController.m
//  xinhua_sx
//
//  Created by love on 14-8-13.
//  Copyright (c) 2014年 dangyangyang. All rights reserved.
//

#import "gerenViewController.h"
#import "AFNetworking.h"
#import "修改密码.h"
#import "UIImageView+AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "提交申请修改.h"
#import "修改个人信息.h"
#import "MBProgressHUD.h"
@interface gerenViewController ()
{
    MBProgressHUD* HUD;
}
@property (nonatomic, strong) UILabel* usreL;
@property (nonatomic, strong) UILabel* nameL;
@property (nonatomic, strong) UIImageView* ve;
@end

@implementation gerenViewController
@synthesize usreL;
@synthesize ve;
@synthesize nameL;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UILabel* l1 = [[UILabel alloc] initWithFrame:CGRectMake(20, 80, 100, 20)];
    l1.text  = @"账号(未认证)";
    l1.font = [UIFont systemFontOfSize:15];
    l1.backgroundColor = [UIColor clearColor];
    [self.view addSubview:l1];
    UIView* v1 = [[UIView alloc] initWithFrame:CGRectMake(20, 150, 280, 1)];
    v1.backgroundColor = [UIColor grayColor];
    [self.view addSubview:v1];
    UILabel* l2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 150, 100, 20)];
    l2.text  = @"用户名";
    l2.font = [UIFont systemFontOfSize:15];
    l2.backgroundColor = [UIColor clearColor];
    [self.view addSubview:l2];
    self.usreL = [[UILabel alloc] initWithFrame:CGRectMake(170, 150, 80, 20)];
    self.usreL.font = [UIFont systemFontOfSize:15];
    self.usreL.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.usreL];
    self.nameL = [[UILabel alloc] initWithFrame:CGRectMake(170, 170, 80, 20)];
    self.nameL.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:self.nameL];
    
    UIView* v2 = [[UIView alloc] initWithFrame:CGRectMake(20, 170, 280, 1)];
    v2.backgroundColor = [UIColor grayColor];
    [self.view addSubview:v2];
    
    UILabel* l3 = [[UILabel alloc] initWithFrame:CGRectMake(20, 170, 100, 20)];
    l3.text  = @"姓名";
    l3.font = [UIFont systemFontOfSize:15];
    l3.backgroundColor = [UIColor clearColor];
    [self.view addSubview:l3];
    UIView* v3 = [[UIView alloc] initWithFrame:CGRectMake(20, 190, 280, 1)];
    v3.backgroundColor = [UIColor grayColor];
    [self.view addSubview:v3];
    UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(20, 190, 200, 20)];
    [button addTarget:self action:@selector(shezhimima:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel* l4 = [[UILabel alloc] initWithFrame:CGRectMake(20, 190, 100, 20)];
    l4.text  = @"修改密码";
    l4.font = [UIFont systemFontOfSize:15];
    //l4.backgroundColor = [UIColor clearColor];
    UIGestureRecognizer* tap = [[UIGestureRecognizer alloc] initWithTarget:self action:@selector(shezhimima:)];
    [l4 addGestureRecognizer:tap];
    l4.userInteractionEnabled = YES;
  
    [self.view addSubview:l4];
    [self.view addSubview:button];
    [button setBackgroundColor:[UIColor clearColor]];
    UIView* v4 = [[UIView alloc] initWithFrame:CGRectMake(20, 210, 280, 1)];
    v4.backgroundColor = [UIColor grayColor];
    [self.view addSubview:v4];
    v1.alpha = 0.5;
    v2.alpha = 0.5;
    v3.alpha = 0.5;
    v4.alpha = 0.5;//file:///Users/love/Desktop/xinhua2.0/xinhua_sx/Home/base_detail_default_pic.png
    
    self.ve = [[UIImageView alloc] initWithFrame:CGRectMake(220, 68, 60, 80)];
    ve.contentMode = UIViewContentModeScaleToFill;
    ve.image = [UIImage imageNamed:@"base_detail_default_pic.png"];
    UIGestureRecognizer* tap1  = [[UIGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    [ve addGestureRecognizer:tap1];
    UIButton* button34 = [[UIButton alloc] initWithFrame:CGRectMake(220, 68, 60, 80)];
    [button34 addTarget:self action:@selector(tap) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button34];
    [button34 setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:ve];
    [self loadGr];
    UIButton* button1 = [[UIButton alloc] initWithFrame:CGRectMake(10, 350, 145, 30)];
    [button1 addTarget:self action:@selector(xiugai1) forControlEvents:UIControlEventTouchUpInside];
    [button1 setTitle:@"修改个人信息" forState:UIControlStateNormal];
    [self.view addSubview:button1];
    UIButton* button2 = [[UIButton alloc] initWithFrame:CGRectMake(165, 350, 145, 30)];
    [button2 addTarget:self action:@selector(xiugai2) forControlEvents:UIControlEventTouchUpInside];
    [button2 setTitle:@"提交修改申请" forState:UIControlStateNormal];
    [self.view addSubview:button2];
    [button1 setBackgroundColor:[gerenViewController colorWithHexString:@"#A6C4E8"]];
    [button2 setBackgroundColor:[gerenViewController colorWithHexString:@"#A6C4E8"]];
    [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //Do any additional setup after loading the view.
}
+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
-(void)tap
{
    NSLog(@"222");
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:@"选取图片或拍照"
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"拍照", @"从相册选取",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}
-(void)xiugai1
{
    gerenxiugai* vc = [[gerenxiugai alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)xiugai2
{
    shenqinxiugai* vc = [[shenqinxiugai alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)loadGr
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    NSString* uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"UID"];
    
    NSString* sting = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/update-%@.html",uid];
     [manager GET:sting parameters:nil success:^(AFHTTPRequestOperation*operation, id responseObject) {
     id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
     options:NSJSONReadingAllowFragments
     error:nil];
     NSLog(@"json = %@",jsonObject);
         self.usreL.text = [jsonObject objectForKey:@"name"];
         self.nameL.text = [jsonObject objectForKey:@"nickName"];
         //[self.ve setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://183.203.18.45:7001%@",jsonObject[@"qRcodePath"]]] placeholderImage:[UIImage imageNamed:@"base_detail_default_pic.png"]];
         [ve setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://183.203.18.45:7001%@",jsonObject[@"imagePath"]]] placeholderImage:[UIImage imageNamed:@"base_detail_default_pic.png"]];
     } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
     NSLog(@"error = %@",error);
     }];

}

-(void)shezhimima:(id)sender
{
    NSLog(@"22");
    xiugaimimacontroller* v1 = [[xiugaimimacontroller alloc] init];
    //UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:v1];
    [self.navigationController pushViewController:v1 animated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 选取图片
- (void)pickPhoto:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:@"选取图片或拍照"
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"拍照", @"从相册选取",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        //拍照
        
        [self pickPhotoWithSource:UIImagePickerControllerSourceTypeCamera];
        return;
        
    }
    if (buttonIndex == 1) {
        // 选取图片
        [self pickPhotoWithSource:UIImagePickerControllerSourceTypePhotoLibrary];
        
        return;
        
    }
    return;
}

- (void)pickPhotoWithSource:(UIImagePickerControllerSourceType )source
{
    //创建图片选择器
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    
    //指定源类型前，检查图片源是否可用
    if ([UIImagePickerController isSourceTypeAvailable:source])
    {
        //指定源的类型
        imagePicker.sourceType = source;
        
        //在选定图片之前，用户可以简单编辑要选的图片。包括上下移动改变图片的选取范围，用手捏合动作改变图片的大小等。
        imagePicker.allowsEditing = YES;
        
        //实现委托，委托必须实现UIImagePickerControllerDelegate协议，来对用户在图片选取器中的动作
        imagePicker.delegate = self;
        
        //设置完iamgePicker后，就可以启动了。用以下方法将图像选取器的视图“推”出来
        [self presentModalViewController:imagePicker animated:YES];
        
        
    }
    else
    {
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:nil message:@"相机不能用" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [alert show];
        
    }
}

#pragma  mark UIImagePickerControllerDelegate协议的方法

//用户点击图像选取器中的“cancel”按钮时被调用，这说明用户想要中止选取图像的操作
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissModalViewControllerAnimated:YES];
}

//用户点击选取器中的“choose”按钮时被调用，告知委托对象，选取操作已经完成，同时将返回选取图片的实例
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    
    //上传图片
    
    ve.image= image;
    //[_photo setImage:_image forState:UIControlStateNormal];
    //    NSLog(@"image %@",image);
    [self shangchuan];
    [picker dismissModalViewControllerAnimated:YES];
    
} 
-(void)shangchuan
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
         NSString* uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"UID"];
    if (!uid)
    {
        return;
    }
    
    // NSLog(@"dishi  =%@",_dizhistring);
    //NSDictionary* dic = @{@"code":@"149725", @"name":t0.text, @"password":t1.text, @"nickname":t3.text, @"phone":t4.text,@"email":t5.text,@"userRegIP":@"192.168.1.11",@"longitude":@"1",@"latitude":@"1"};
    NSString* st = [NSString stringWithFormat:@"http://183.203.18.45:7001/xinhua/m/imageSave.html"];
    NSLog(@"st = %@",st);
    [HUD hide:YES];
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.labelText = @"正在保存";
    HUD.dimBackground = YES;
    [self.view addSubview:HUD];
    [HUD show:YES];
    //?%@=%@&%@=%@&%@=%@&%@=%@&%@=%@&%@=%@&%@=%@&%@=%@&marriage=否&frontUserId=%@",NAme[0],t0.text,NAme[1],t1.text,NAme[2],t2.text,NAme[3],t3.text,NAme[4],t4.text,NAme[5],t5.text,NAme[6],t6.text,NAme[7],t7.text,uid
    //NSDictionary* dic = @{NAme[0]:t0.text,NAme[1]:t1.text,NAme[2]:t2.text,NAme[3]:t3.text,NAme[4]:t4.text,NAme[5]:t5.text,NAme[6]:t6.text,NAme[7]:t7.text,NAme[8]:t8.text ,NAme[9]:t9.text ,NAme[10]:t10.text ,@"frontUserId":uid,@"officeNumber":@"一级部门",@"family":@"family",@"lifeArae":@"寿阳",@"code":@"140725",@"title":@"公务员"};
   // NSLog(@"dic = %@",dic);
    st = [st stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [manager  POST:st  parameters:[NSDictionary dictionaryWithObjectsAndKeys:uid,@"frontUserId", nil]  constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
        
        NSData * data =  UIImagePNGRepresentation(ve.image); //将拍下的图片转化成data
        
        [formData appendPartWithFileData:data name:@"uploadedfile" fileName:@"1" mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject){
        
        id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
        NSLog(@"json = %@",jsonObject);
        [HUD hide:YES];
        NSString* string = [NSString stringWithFormat:@"%@",jsonObject[@"result"]];
        if ([string isEqualToString:@"success"])
        {
            UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:jsonObject[@"message"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            v1.tag = 100086;
            [v1 show];
            // NSUserDefaults* de = [NSUserDefaults standardUserDefaults];
            // [de removeObjectForKey:@"UID"];
            // [de synchronize];
            
            NSLog(@"1222");
            //  [[NSNotificationCenter defaultCenter] postNotificationName:@"Logout1" object:nil];
            NSLog(@"2233");
        }
        else
        {
            UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:jsonObject[@"message"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [v1 show];
        }

       
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [HUD hide:YES];
        UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"上传失败!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [v1 show];
        NSLog(@"Error: %@", error);
        
    }];
    /*[manager POST:st parameters:[NSDictionary dictionaryWithObjectsAndKeys:uid,@"frontUserId",@"140725",@"code", nil] success:^(AFHTTPRequestOperation*operation, id responseObject) {
        id jsonObject = [NSJSONSerialization JSONObjectWithData:operation.responseData
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
        NSLog(@"json = %@",jsonObject);
        [HUD hide:YES];
        NSString* string = [NSString stringWithFormat:@"%@",jsonObject[@"result"]];
        if ([string isEqualToString:@"success"])
        {
            UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:jsonObject[@"message"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            v1.tag = 100086;
            [v1 show];
            // NSUserDefaults* de = [NSUserDefaults standardUserDefaults];
            // [de removeObjectForKey:@"UID"];
            // [de synchronize];
            
            NSLog(@"1222");
            //  [[NSNotificationCenter defaultCenter] postNotificationName:@"Logout1" object:nil];
            NSLog(@"2233");
        }
        else
        {
            UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:jsonObject[@"message"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [v1 show];
        }
        //self.usreL.text = [jsonObject objectForKey:@"name"];
        //self.nameL.text = [jsonObject objectForKey:@"nickName"];
        //[self.ve setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://183.203.18.45:7001%@",jsonObject[@"qRcodePath"]]] placeholderImage:[UIImage imageNamed:@"base_detail_default_pic.png"]];
    } failure:^(AFHTTPRequestOperation *operation, NSError*error) {
        [HUD hide:YES];
        UIAlertView* v1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"上传失败!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [v1 show];
        NSLog(@"error = %@",error);
    }];*/

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
